package curtain.whynot.frame.basic.csv.excle;



import com.whynot.frame.basic.util.DateUtils;
import com.whynot.frame.basic.util.StringUtils;
import curtain.whynot.frame.basic.csv.Converter;
import curtain.whynot.frame.basic.csv.config.CsvTable;
import curtain.whynot.frame.basic.csv.impl.CsvExportImpl;
import curtain.whynot.frame.basic.csv.parser.AbstractParser;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component("excleExport")
public class ExcleExportImpl extends CsvExportImpl implements ExcleExport{
	AbstractParser parser = new ExcelWriter();

	public AbstractParser getParser() {
		return parser;
	}

	public void setParser(AbstractParser parser) {
		super.setParser(parser);
	}
	/**
	 * 导出时使用
	 * @param data
	 *            必须是map或者JAVABEAN
	 * @param fields
	 *            必须是map的key值或者JAVABEAN属性
	 * @return
	 */
	@Override
	protected Object[] getRow(Object data, List<? extends CsvTable.CsvField> fields) {
		List<Object> row = new ArrayList<Object>(fields.size());
		for (CsvTable.CsvField csvField : fields) {
			String type = csvField.getType();
			String format = csvField.getFormat();
			Object val = getProperty(data, csvField.getName());


			// 日期格式转化
			if (CsvTable.DATE.equals(type)) {
				val = DateUtils.format((Date) val, CsvTable.DATE_FORMAT);
			}

			if (CsvTable.DATE_TIME.equals(type)) {
				val = DateUtils.format((Date) val, CsvTable.DATE_TIME_FORMAT);
			}

			// 数字格式转化
			if (CsvTable.NUMBER.equals(type)) {
				if (!StringUtils.isNullOrBlank(format)) {
					DecimalFormat df1 = new DecimalFormat(format);
					val = df1.format(val);
				}
			}
			// 自定义转化
			if (CsvTable.CUSTOM.equals(type)) {
				if (!StringUtils.isNullOrBlank(format)) {
					if(format.indexOf(METHOD_NAME_SPLIT) != -1) {
						val = invokeMethod(format,  val  );
					}else {
						Converter convert = getConverter(format);
						if (convert != null) {
							val = convert.convert(val);
						}
					}
				}
			}
			row.add(val);
		}
		return row.toArray();
	}

}
